import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import { useState, useCallback, useEffect } from 'react';
/**
 * 获取远程数据
 * @param request  通过 axios, umi-request 等获取远程数据
 * @param options options.manual boolean 是否手动发起请求 options.useData boolean 是否返回res.data options.defaultData any 请求失败返回的默认值
 * @returns fetch 发起远程请求
 * @returns loading 远程请求状态
 * @returns data 转换处理后的远程数据
 */
function useFetch(request, options) {
  var _ref = options || {},
    manual = _ref.manual,
    defaultData = _ref.defaultData;
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    loading = _useState2[0],
    setLoading = _useState2[1];
  var _useState3 = useState(defaultData),
    _useState4 = _slicedToArray(_useState3, 2),
    data = _useState4[0],
    setData = _useState4[1];
  //@ts-ignore
  var fetch = useCallback(function () {
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    setLoading(true);
    return new Promise(function (resolve, reject) {
      request.apply(void 0, args).then(function (res) {
        setLoading(false);
        var result = res;
        if (options === null || options === void 0 ? void 0 : options.useData) {
          if (res === null || res === void 0 ? void 0 : res.success) {
            result = res.data;
          } else {
            result = null;
          }
        }
        // 如果 result 为 null 或 undefined，使用 options.defaultData 代替
        if ((result === null || result === undefined) && options && 'defaultData' in options) {
          result = defaultData;
        }
        setData(result);
        resolve(result);
      }).catch(function (err) {
        setLoading(false);
        setData(defaultData);
        reject(err);
      });
    });
  },
  // loading 会导致 fetch 更新，不利于 fetch 作为其他 hooks 的依赖
  []);
  useEffect(function () {
    if (!manual) {
      fetch();
    }
  }, [manual]);
  return {
    fetch: fetch,
    loading: loading,
    data: data,
    mutate: setData
  };
}
export default useFetch;